package com.coffee.yuyue.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.coffee.yuyue.entity.Product;
import com.coffee.yuyue.security.MyUserDetails;
import com.coffee.yuyue.service.ProductService;

@Controller
@RequestMapping(value="/product")
public class ProductController {
	@Autowired
	private ProductService productService;
	
	@RequestMapping(value="/list",method = RequestMethod.GET)
    public ModelAndView login(@RequestParam(required=true,defaultValue="0")Integer pageNo) {
		MyUserDetails userDetails = (MyUserDetails) SecurityContextHolder.getContext()
			    .getAuthentication()
			    .getPrincipal();
		PageRequest pageRequest=new PageRequest(pageNo, 20);
		Page<Product> page=productService.findByUserId(userDetails.getId(),pageRequest);
		ModelAndView mv=new ModelAndView("product/list");
		mv.addObject("page",page);
        return mv;
    }
	@RequestMapping(value="/add",method = RequestMethod.GET)
	public String add() {
		return "product/add";
	}
	@RequestMapping(value="/add",method = RequestMethod.POST)
	public String addFrom(Product product) {
		MyUserDetails userDetails = (MyUserDetails) SecurityContextHolder.getContext()
			    .getAuthentication()
			    .getPrincipal();
		product.setUserId(userDetails.getId());
		product.setIsDel(false);
		productService.add(product);
		return "common/success";
	}
	@RequestMapping(value="/delete/{productId}",method = RequestMethod.POST)
	@ResponseBody
	public boolean delete(@PathVariable Long productId) {
		MyUserDetails userDetails = (MyUserDetails) SecurityContextHolder.getContext()
				.getAuthentication()
				.getPrincipal();
		Product product=productService.get(productId);
		if (product!=null&&product.getUserId()==userDetails.getId()) {
			productService.delete(product);
			return true;
		}
		return false;
	}
}
